package com.gjy.sb.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-08-19 21:48:18
 */
@Configuration
public class OrderDisruptorConfig {

    @Resource
    private OrderEventHandler orderEventHandler;

    /**
     * 创建并配置 Disruptor 实例
     */
    @Bean(destroyMethod = "shutdown") // 确保应用关闭时优雅关闭 Disruptor
    public Disruptor<OrderEvent> disruptor() {
        // 1. Ring Buffer 大小，必须是 2 的幂，提高取模运算效率
        int ringBufferSize = 1024;
        // 2. 创建线程工厂，用于创建消费者线程
        ThreadFactory threadFactory = r -> {
            Thread thread = new Thread(r);
            thread.setName("disruptor-consumer-thread-" + new AtomicInteger().incrementAndGet());
            thread.setDaemon(true); // 设置为守护线程
            return thread;
        };
        // 3. 创建 Disruptor 实例
        // ProducerType.SINGLE: 单生产者模式（性能更高）
        // WaitStrategy: 使用 YieldingWaitStrategy，在低延迟和 CPU 占用间取得平衡
        Disruptor<OrderEvent> disruptor = new Disruptor<>(
                new OrderEventFactory(), // 事件工厂
                ringBufferSize,
                threadFactory,
                ProducerType.SINGLE,
                new YieldingWaitStrategy() // 等待策略
        );
        // 4. 设置事件处理器（消费者）
        // Disruptor 可以支持多个消费者（并行处理）或消费者链（顺序处理）
        disruptor.handleEventsWith(orderEventHandler);
        // 5. 启动 Disruptor
        disruptor.start();
        return disruptor;
    }

    /**
     * 提供一个 RingBuffer 的 Bean，方便生产者发布事件
     */
    @Bean
    public RingBuffer<OrderEvent> ringBuffer(Disruptor<OrderEvent> disruptor) {
        return disruptor.getRingBuffer();
    }

}
